#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
pthread_mutex_t lock;
int tickets=100;

void* get_ticket(void* arg){
    while(1){
        usleep(1000);
        pthread_mutex_lock(&lock);
        if(tickets>0){
            usleep(1000);
            printf("[thread %d] get ticket NO:%d\n",(long)arg,tickets);
            tickets--;
            pthread_mutex_unlock(&lock);
        }
        else{
            pthread_mutex_unlock(&lock);

            break;
        }
    }
}
int main(){
    pthread_t tid[4];
    pthread_mutex_init(&lock,NULL);
    int i=0;
    for(;i<4;++i){
        pthread_create(tid+i,NULL,get_ticket,(void*)i);
    }

    for(i=0;i<4;++i){
        pthread_join(tid[i],NULL);
    }
    pthread_mutex_destroy(&lock);
    return 0;
}
